package com.hp.service.chain;

import com.hp.model.chain.OrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hp
 */
@Service
public class ValidationChain {


    // Spring自动注入所有实现
    private final List<ValidationHandler> handlers;

    @Autowired
    public ValidationChain(List<ValidationHandler> handlers) {

        // 排序逻辑：按 @Order 注解的值排序，未标注的排在最后
        this.handlers = handlers.stream()
                .sorted(Comparator.comparingInt(this::getAnnotationValue))
                .collect(Collectors.toList());

        assembleChain();
    }

    private int getAnnotationValue(ValidationHandler handler) {
        Order annotation = handler.getClass().getAnnotation(Order.class);
        return (annotation != null) ? annotation.value() : Integer.MAX_VALUE;
    }

    private void assembleChain() {
        for (int i = 0; i < handlers.size() - 1; i++) {
            handlers.get(i).setNext(handlers.get(i + 1));
        }
    }

    public void validateOrder(OrderRequest request) {
        if (handlers.isEmpty()) {
            throw new IllegalStateException("No validation handlers found.");
        }
        handlers.getFirst().validate(request);
    }
}